package com.party.web.web.controller.photo;

import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.photo.PhotoProject;
import com.party.core.model.photo.PhotosImgInfo;
import com.party.core.model.photo.PhotosImgInfoWithResource;
import com.party.core.model.photo.PhotosTag;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.photo.IPhotoProjectService;
import com.party.core.service.photo.IPhotosImgInfoService;
import com.party.core.service.photo.IPhotosTagService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.photo.AlbumBizService;
import com.party.web.biz.photo.ImgInfoBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 相册分类
 * @Author: yangshoukun
 * @Date: 2018/5/30 14:21
 */
@Controller
@RequestMapping("/photo/album")
public class AlbumController {

    @Autowired
    private AlbumBizService albumBizService;

    @Autowired
    private IPhotosTagService photosTagService;

    @Autowired
    private IPhotoProjectService photoProjectService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private ImgInfoBizService imgInfoBizService;

    @Autowired
    private IPhotosImgInfoService photosImgInfoService;

    @Autowired
    private IMemberGroupService memberGroupService;

    /**
     * 列表
     * @param input
     * @param photosTag
     * @param page
     * @return
     */
    @DataControl
    @RequestMapping("/list")
    public ModelAndView list(CommonInput input, @ControlParam(table = "xc_photos", column = "member_id", getMethodName = "getPhotosId") PhotosTag photosTag, Page page) {
        final String pattern = "yyyy-MM-dd";

        page.setLimit(20);

        ModelAndView mv = new ModelAndView("photo/photosTag");

        Map<String, Object> params = CommonInput.appendParams(input);
        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, pattern.length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, pattern.length()));
        }

        List<PhotosTag> list = albumBizService.list(params, photosTag, page);

        PhotoProject photoProject = photoProjectService.get(photosTag.getPhotosId());

        mv.addObject("input", input);
        mv.addObject("photosTag", photosTag);
        mv.addObject("photoProject", photoProject);
        mv.addObject("page", page);
        mv.addObject("list", list);
        return mv;
    }

    /**
     * 添加/编辑页面
     * @param id
     * @return
     */
    @RequestMapping("/addAlbum")
    public ModelAndView addAlbum(String id, String photosId) {
        ModelAndView mv = new ModelAndView("/photo/addAlbum");
        PhotosTag photosTag = new PhotosTag();
        if (StringUtils.isNotEmpty(id)) {
            photosTag = photosTagService.get(id);
        }
        photosTag.setPhotosId(photosId);
        mv.addObject("photosTag", photosTag);
        return mv;
    }
    /**
     * 添加/编辑页面
     * @param id
     * @return
     */
    @RequestMapping("/third/addAlbum")
    public ModelAndView thirdAddAlbum(String id, String photosId) {
        ModelAndView mv = new ModelAndView("/photo/thirdAddAlbum");
        PhotosTag photosTag = new PhotosTag();
        if (StringUtils.isNotEmpty(id)) {
            photosTag = photosTagService.get(id);
        }
        photosTag.setPhotosId(photosId);
        mv.addObject("photosTag", photosTag);
        return mv;
    }

    /**
     * 保存
     * @param photosTag
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/save", "/third/save"})
    public AjaxResult save(PhotosTag photosTag) {
        try {
            albumBizService.save(photosTag);
            return AjaxResult.success("保存成功");
        } catch (BusinessException be) {
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("保存异常");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult delete(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("id不能为空");
            }
            albumBizService.delete(id);
            return AjaxResult.success("删除成功");
        } catch (BusinessException be) {
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("删除异常");
        }
    }

    /**
     * 添加照片
     * @param photosId
     * @param albumId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/addPic", "/third/addPic"})
    public AjaxResult addPic(String photosId, String albumId, String urls, String imgResourceIds) {
        try {
            albumBizService.addPic(photosId, albumId, urls, imgResourceIds);
            return AjaxResult.success("添加照片成功");
        } catch (BusinessException be) {
            be.printStackTrace();
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("添加照片异常");
        }
    }

    /**
     * 分类列表
     * @param photosId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"/tags", "/third/tags"})
    public AjaxResult tags(String photosId) {
        try {
            List<PhotosTag> outputs = albumBizService.tags(photosId);
            return AjaxResult.success(outputs);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取分类列表异常");
        }
    }

    /**
     * 第三方用户获取相册分类
     *
     * @return
     */
    @RequestMapping("/third/list")
    public ModelAndView thirdlist(CommonInput input, @ControlParam(table = "xc_photos", column = "member_id", getMethodName = "getPhotosId") PhotosTag photosTag, Page page) {
        final String pattern = "yyyy-MM-dd";

        page.setLimit(20);

        ModelAndView mv = new ModelAndView("photo/thirdAlbumList");

        Map<String, Object> params = CommonInput.appendParams(input);
        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, pattern.length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, pattern.length()));
        }

        List<PhotosTag> list = albumBizService.list(params, photosTag, page);

        PhotoProject photoProject = photoProjectService.get(photosTag.getPhotosId());

        String memberId = photoProject.getMemberId();
        MemberGroup member = memberGroupService.get(memberId);
        photoProject.setMemberName(member.getRealname());
        String filePath = fileBizService.getUploadCIPath(memberId, "photo");
        String url = cosBizService.getPreviewPictureUrl(filePath + photoProject.getId());

        MemberGroup currentUser = RealmUtils.getCurrentUser();
        mv.addObject("currentUserId", currentUser.getId());
        mv.addObject("qrcodeUrl", url);
        mv.addObject("input", input);
        mv.addObject("photosTag", photosTag);
        mv.addObject("photoProject", photoProject);
        mv.addObject("page", page);
        mv.addObject("list", list);
        return mv;
    }

    /**
     * 打开相册上传图片
     * @param id 相册id
     * @param tagId 分类id
     * @return
     */
    @RequestMapping(value = "/third/photo/uploadImg")
    public ModelAndView thirdPhotoUpload(String compress, String id, String tagId) {
        ModelAndView mv = new ModelAndView("photo/thirdUploadImg");
        mv.addObject("id", id);
        mv.addObject("tagId", tagId);
        return mv;
    }

    /**
     * 照片列表
     * @param albumId
     * @param page
     * @return
     */
    @RequestMapping("third/Imglist")
    public ModelAndView thirdImgList(String albumId, Page page) {
        if (StringUtils.isEmpty(albumId)) {
            return new ModelAndView(Constant.ERROR_402);
        }
        PhotosTag tag = photosTagService.get(albumId);
        if (null == tag) {
            return new ModelAndView(Constant.ERROR_402);
        }
        ModelAndView mv;

        List<PhotosImgInfoWithResource> list = null;
        List<Map<String, Object>> listTime = null;
        if (PhotosTag.ALBUM_TIME_LINE.equals(tag.getName())) {
            page.setLimit(5);
            mv = new ModelAndView("/photo/thirdPhotoPic-time");
            listTime = imgInfoBizService.listTimeLine(albumId, page);
            Integer count = photosImgInfoService.getCount(tag.getPhotosId(), null);
            mv.addObject("myCount", count);
        } else {
            page.setLimit(40);
            mv = new ModelAndView("/photo/thirdPhotoPic");
            list = imgInfoBizService.list(albumId, page);
        }
        MemberGroup currentUser = RealmUtils.getCurrentUser();
        PhotoProject photoProject = photoProjectService.get(tag.getPhotosId());

        mv.addObject("memberId", currentUser.getId());
        mv.addObject("tag", tag);
        mv.addObject("listTime", listTime);
        mv.addObject("photoProject", photoProject);
        mv.addObject("page", page);
        mv.addObject("list", list);
        return mv;
    }


    /**
     * 判断是否是自己上传的图片
     * @param imgIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"third/isThirdImg"})
    public AjaxResult isThirdImg(String imgIds) {
        if(StringUtils.isEmpty(imgIds)){
            return AjaxResult.error("图片id不能为空");
        }
        try {
            String[] imgArray = imgIds.split(",");
            ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(imgArray));

            MemberGroup currentUser = RealmUtils.getCurrentUser();
            List<PhotosImgInfo> outputs = photosImgInfoService.queryThirdImgList(currentUser.getId(),arrayList);

            boolean bol = arrayList.size()==outputs.size();

            return AjaxResult.success(bol);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("获取分类列表异常");
        }
    }

    /**
     * 删除照片
     * @param tagId: 分类id
     * @param imgIds: 图片id
     * @return
     */
    @ResponseBody
    @RequestMapping("third/delete")
    public AjaxResult delete(String tagId, String imgIds) {
        try {
            imgInfoBizService.delete(tagId, imgIds);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("删除照片异常");
        }
    }

    /**
     * 移动照片获取分类
     * @param photosId
     * @return
     */
    @RequestMapping("third/toMove")
    public ModelAndView toMove(String photosId ,String tagId) {
        ModelAndView mv = new ModelAndView("/photo/thirdMoveImg");
        List<PhotosTag> list = imgInfoBizService.getTagsByPhotosId(photosId);
        mv.addObject("tags", list);
        mv.addObject("photosId", photosId);
        mv.addObject("tagId", tagId);
        return mv;
    }

    /**
     * 移动照片到某个相册
     * @param imgIds
     * @param tagIds
     */
    @ResponseBody
    @RequestMapping("third/moveImg")
    public AjaxResult moveImg(String imgIds, String tagIds, String tagId) {
        try {
            imgInfoBizService.moveImg(imgIds, tagIds, tagId, true);
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("移动照片异常");
        }
    }

    /**
     * 设为精选
     * @param imgIds
     * @return
     */
    @ResponseBody
    @RequestMapping(value = {"third/setChoiceness"})
    public AjaxResult setChoiceness(String imgIds, String photosId) {
        try {
            PhotosTag param = new PhotosTag();
            param.setPhotosId(photosId);
            param.setName(PhotosTag.ALBUM_CHOICENESS);
            PhotosTag tag = photosTagService.findByName(param);
            if (null != tag) {
                imgInfoBizService.moveImg(imgIds, tag.getId(), null, false);
            }
            return AjaxResult.success();
        } catch (BusinessException be) {
            return AjaxResult.error(be.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("设为精选异常");
        }
    }
}
